<template>
  <div class="role-management">
    <!-- 筛选及搜索区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.keywords"
                placeholder="输入角色名称"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" style="text-align: left; margin-top: 12px">
          <el-button type="primary" @click="handleAddRole">添加角色</el-button>
        </el-col>
      </el-row>
    </div>
<el-dialog
  title="添加角色"
  :visible.sync="addRoleDialogVisible"
  width="30%"
  @close="handleAddRoleDialogClose"
>
  <el-form
    :model="addRoleForm"
    :rules="addRoleRules"
    ref="addRoleForm"
    label-width="100px"
  >
    <el-form-item label="角色编码" prop="roleCode">
      <el-input v-model="addRoleForm.roleCode"></el-input>
    </el-form-item>
    <el-form-item label="角色昵称" prop="name">
      <el-input v-model="addRoleForm.name"></el-input>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="addRoleDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAddRoleSubmit">确认提交</el-button>
    </span>
  </template>
</el-dialog>
    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
      :border="false"
    >
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="角色昵称"
        min-width="70"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="roleCode"
        label="角色编码"
        min-width="70"
        align="center"
      ></el-table-column>
      <!-- <el-table-column
        prop="status"
        label="状态"
        min-width="100"
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="130"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        min-width="130"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            type="text"
            style="color: red"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 权限配置侧边栏 -->
    <el-drawer
    title="角色权限配置"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="50%"
    :before-close="handleDrawerClose"
  >
    <!-- 权限菜单容器 -->
    <div class="permission-menu-container">
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
        style="margin-bottom: 20px"
      >
        全选权限
      </el-checkbox>

        <!-- 递归渲染权限菜单 -->
        <el-menu
        ref="permissionMenu"
        class="custom-sidebar-menu"
        :default-openeds="defaultOpeneds"
        mode="vertical"  
      >
        <template v-for="item in permissionMenuData">
          <permission-sidebar-item
            :key="item.id"
            :item="item"
            :level="1"
            :checked-keys="checkedKeys"
                  :parent-id="null"
            @update:checkedKeys="updateCheckedKeys"
          />
        </template>
      </el-menu>
      </div>

      <div style="text-align: right; margin-top: 20px">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-drawer>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import PermissionSidebarItem from "./edit.vue";

export default {
  name: "RoleManagement",
  components: {
    PermissionSidebarItem,
  },
  data() {
    return {
      searchForm: {
        keywords: "",
      },
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      drawerVisible: false,
      currentRole: null,
      permissionMenuData: [], // 所有权限菜单数据
      checkedKeys: [], // 已选中的权限ID
      checkAll: false,
      isIndeterminate: false,
      defaultOpeneds: [], // 默认展开的菜单
       addRoleDialogVisible: false, // 添加角色弹窗显示状态
    addRoleForm: { // 添加角色表单数据
      roleCode: '', 
      name: ''
    },
    addRoleRules: { // 表单校验规则
      roleCode: [
        { required: true, message: '请输入角色编码', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入角色昵称', trigger: 'blur' }
      ]
    }
    };
  },
  created() {
    // 初始化页面数据
    this.fetchRoleList();
    this.fetchAllPermissions();
  },
  watch: {
    checkedKeys(val) {
      // 计算全选状态
      const allPermissionIds = this.getAllPermissionIds();
      this.checkAll = val.length === allPermissionIds.length && val.length > 0;
      this.isIndeterminate =
        val.length > 0 && val.length < allPermissionIds.length;
    },
  },
  methods: {
     handleAddRoleSubmit() {
    this.$refs.addRoleForm.validate(async (valid) => {
      if (valid) {
        try {
          const res = await this.$request.post('/system/sysRole/add', {
            roleCode: this.addRoleForm.roleCode,
            name: this.addRoleForm.name
          });
          if (res.code === 200) {
            this.$message.success('角色添加成功');
            this.addRoleDialogVisible = false;
            // 重新获取角色列表
            this.fetchRoleList();
          } else {
            this.$message.error(`添加失败: ${res.msg || '未知错误'}`);
          }
        } catch (error) {
          console.error('添加角色失败:', error);
          this.$message.error('添加角色失败，请重试');
        }
      }
    });
  },
  handleAddRoleDialogClose() {
    // 关闭弹窗时重置表单校验状态
    this.$refs.addRoleForm.resetFields();
  },
    // 获取角色列表
    async fetchRoleList() {
      this.tableLoading = true;
      try {
        const res = await this.$request.get("/system/sysRole/list", {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            keyword: this.searchForm.keywords,
          },
        });

        if (res.code === 200) {
          console.log("dad", res);
          this.tableData = res.data.records;
          this.totalCount = Number(res.data.total);
        }
      } catch (error) {
        console.error("获取角色列表失败:", error);
        this.$message.error("获取角色列表失败，请重试");
      } finally {
        this.tableLoading = false;
      }
    },

    // 获取所有权限菜单
    async fetchAllPermissions() {
      try {
        const res = await this.$request.get("/system/sysMenu/all");
        if (res.code === 200) {
          this.permissionMenuData = res.data;
          console.log("权限菜单数据：", this.permissionMenuData);
        }
      } catch (error) {
        console.error("获取权限菜单失败:", error);
        this.$message.error("获取权限菜单失败，请重试");
      }
    },

    // 获取角色已有权限
    async fetchRolePermissions(roleId) {
      try {
        const res = await this.$request.get(
          `/system/sysRole/${roleId}/permissions`
        );
        if (res.code === 200) {
          console.log("111", res);
          // 返回的数据结构应该是 { permissionIds: [1, 2, 3] }
          return res.data || [];
        }
        return [];
      } catch (error) {
        console.error("获取角色权限失败:", error);
        this.$message.error("获取角色权限失败，请重试");
        return [];
      }
    },

    // 点击编辑按钮
    async handleEdit(row) {
        const button = document.activeElement; // 获取当前点击的按钮
        if (button && button.blur) {
    button.blur(); // 立即移除按钮聚焦态
    document.body.focus(); // 让body接管焦点
  }

    this.currentRole = row;
    this.drawerVisible = true;

    const loading = this.$loading({
      lock: true,
      text: "正在加载权限数据...",
      target: ".permission-menu-container",
    });

    try {
      // 1. 获取角色已有权限
      const menus = await this.fetchRolePermissions(row.id);
      // 2. 提取ID并转为数字类型
      const permissionIds = menus.map(item => Number(item.id));
      
      // 3. 确保DOM更新后再设置checkedKeys（关键修复）
      this.$nextTick(() => {
        this.checkedKeys = [...permissionIds]; 
        console.log("dadasss1",this.checkedKeys)// 强制数组刷新
        // 4. 强制菜单组件重新渲染
        this.$refs.permissionMenu && this.$refs.permissionMenu.$forceUpdate();
      });

      // 5. 默认展开所有父菜单
      this.defaultOpeneds = this.permissionMenuData
        .filter(item => item.children && item.children.length)
        .map(item => item.id.toString());
    } finally {
 loading.close();
    // 失焦处理：让编辑按钮失去焦点
   
    }    
  },

  // 更新选中的权限（确保响应式）
  updateCheckedKeys(newKeys) {
    this.checkedKeys = [...newKeys];
            console.log("dadasss2",this.checkedKeys)// 强制数组刷新

    // 用新数组替换，触发响应式
  },
    // 获取所有权限ID
    getAllPermissionIds() {
      const ids = [];
      const collectIds = (items) => {
        items.forEach((item) => {
          ids.push(Number(item.id));
          if (item.children && item.children.length > 0) {
            collectIds(item.children);
          }
        });
      };

      collectIds(this.permissionMenuData);
      return ids;
    },

    // 全选/取消全选
    handleCheckAllChange(checked) {
      if (checked) {
        this.checkedKeys = this.getAllPermissionIds();
      } else {
        this.checkedKeys = [];
      }
      this.isIndeterminate = false;
    },

    // 保存权限配置
    async handleSave() {
      if (!this.currentRole) return;

      try {
        const res = await this.$request.post(
          `/system/sysRole/${this.currentRole.id}/permissions`,
           this.checkedKeys,
          
        );

        if (res.code === 200) {
          this.$message.success("权限配置保存成功");
          this.drawerVisible = false;
        } else {
          this.$message.error(`保存失败: ${res.msg || "未知错误"}`);
        }
      } catch (error) {
        console.error("保存权限失败:", error);
        this.$message.error("保存权限失败，请重试");
      }
    },

    // 关闭抽屉时重置状态
    handleDrawerClose() {
      this.checkedKeys = [];
      this.currentRole = null;
    },

    // 其他方法保持不变
    handleSearch() {
      this.currentPage = 1;
      this.fetchRoleList();
    },
    handleAddRole() {
  this.addRoleDialogVisible = true;
  // 重置表单数据
  this.addRoleForm = {
    roleCode: '', 
    name: ''
  };
},
    handleDelete(row) {
        const button = document.activeElement; // 获取当前点击的删除按钮

      this.$confirm("此操作将永久删除该角色，是否继续?", "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await this.$request.delete(`/system/sysRole/${row.id}`);
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.fetchRoleList();
            } else {
              this.$message.error(`删除失败: ${res.msg || "未知错误"}`);
            }
          } catch (error) {
            console.error("删除角色失败:", error);
            this.$message.error("删除角色失败，请重试");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        })
    .catch(() => {
      this.$message.info("已取消删除");
    })
    .finally(() => {
      // 失焦处理：延迟让按钮失去焦点
      if (button && button.blur) {
        setTimeout(() => {
          button.blur();
          document.body.focus();
        }, 100);
      }
    });
},
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchRoleList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchRoleList();
    },
  },
};
</script>

<style scoped>
.role-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-section {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  width: 100%;
}

.permission-menu-container {
  padding: 10px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

/* 菜单样式 */
::v-deep .custom-sidebar-menu {
  --base-indent: 25px; /* 基础缩进量 */
  border-right: none;
}

/* 父菜单标题：根据level动态控制缩进 */
::v-deep .el-submenu__title {
  padding-left: calc(var(--base-indent) * (var(--level) - 1)) !important;
}

/* 子菜单项：比父菜单多一层缩进 */
::v-deep .el-menu-item {
  padding-left: calc(var(--base-indent) * var(--level)) !important;
}

/* 统一字体和颜色 */
::v-deep .el-submenu__title,
::v-deep .el-menu-item {
  font-size: 16px !important;
  font-weight: 500 !important;
  color: #42b983 !important;
}

/* 交互反馈 */
::v-deep .el-submenu__title:hover,
::v-deep .el-menu-item:hover {
  background-color: rgba(66, 185, 131, 0.1) !important;
}

/* 复选框样式调整 */
::v-deep .el-submenu__title .el-checkbox,
::v-deep .el-menu-item .el-checkbox {
  vertical-align: middle;
}
</style>
